﻿using System;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Web;
using System.Web.Services;
using OA.Log;
using OA.Model;
using OA.Utility;

namespace OA.Web.Handler
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class AjaxHandle : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/javascript";
            context.Response.ContentEncoding = Encoding.UTF8;
            string page = context.Request["page"];
            string rows = context.Request["rows"];
            string str = MakeJson(page, rows);
            context.Response.Write(str);
        }

        private static string MakeJson(string page, string rows)
        {
            string strjson;
            try
            {
                JsonReq req = JsonHelper.JsonDeserialize<JsonReq>(JsonHelper.GetPostString());
                UserSession userSession = SessionBox.GetUserSession();
                //if (userSession != null)
                //{
                //    if (!req.Options.ContainsKey("LoginId"))
                //        req.Options.Add("LoginId", userSession.LoginId.ToString(CultureInfo.InvariantCulture));
                //    if (!req.Options.ContainsKey("UserName"))
                //        req.Options.Add("UserName", userSession.LoginName);
                //}
                if (!string.IsNullOrEmpty(page))
                {
                    req.Options.Add("page", page);
                }
                if (!string.IsNullOrEmpty(rows))
                {
                    req.Options.Add("rows", rows);
                }
                req.Options.Add("UserHostAddress", HttpContext.Current.Request.UserHostAddress);
                Assembly ass = Assembly.Load(req.AssemblyName); //利用dll的路径加载,同时将此程序集所依赖的程序集加载进来,需后辍名.dll
                //Assembly.LoadFile("dll文件名"); //只加载指定文件，并不会自动加载依赖程序集.Assmbly.Load 无需后辍名 加载dll后,需要使用dll中某类.
                Type type = ass.GetType(req.ClassName); //利用类型的命名空间和名称获得类型

                object obj = ass.CreateInstance(req.ClassName);
                MethodInfo mi = type.GetMethod(req.Method,
                                               BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
                //通过方法名称获得方法
                strjson = mi.Invoke(obj, new object[] {req}).ToString();
            }
            catch (Exception ex)
            {

                Logger.LogError(ex);
                return ex.Message;
            }
            return strjson;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
